package com.ztom.daily.n2022.m3;

/**
 * Z 字形变换
 * <p>
 * https://leetcode-cn.com/problems/zigzag-conversion/
 *
 * @author ZhangTao
 */
public class Day01Convert {

    /**
     * 0     6      12        18
     * 1   5 7   11 13    17
     * 2 4   8 10   14 16
     * 3     9      15
     * <p>
     * 观察可得:
     * 对 k = i % (2n - 2)进行判断
     * <p>
     * k <= n - 1 时候，s[i] 就属于第 k 行
     * k > n - 1 时候，s[i] 就属于 2n - 2 - k 行
     */
    public String convert(String s, int numRows) {
        if (s == null || s.length() == 0 || numRows <= 0) {
            return null;
        }
        if (numRows == 1) {
            return s;
        }

        StringBuilder[] builders = new StringBuilder[numRows];
        for (int i = 0; i < builders.length; i++) {
            builders[i] = new StringBuilder();
        }
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            int k = i % (2 * numRows - 2);
            if (k < numRows) {
                builders[k].append(chars[i]);
            } else {
                builders[2 * (numRows - 1) - k].append(chars[i]);
            }
        }

        StringBuilder res = new StringBuilder();
        for (StringBuilder builder : builders) {
            res.append(builder);
        }
        return res.toString();
    }
}
